import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_page/game_detail_page_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_round.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_quick_bet_set.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/button/debounce_gesture_detector.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/input/common_text_field.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class WidgetQuickBetSetting extends StatefulWidget {
  const WidgetQuickBetSetting(
      {super.key,
      required this.rows,
      required this.logic,
      required this.gameLogic});

  final GameDetailPageLogic logic;
  final List<ModelQuickBetSet> rows;

  final GameDetailLogic gameLogic;

  @override
  State<WidgetQuickBetSetting> createState() => _WidgetQuickBetSettingState();
}

class _WidgetQuickBetSettingState extends State<WidgetQuickBetSetting> {
  List<ModelQuickBetSet> rows = [];
  List<TextEditingController> controllers = [];

  @override
  void initState() {
    super.initState();
    // 深拷贝传入的数据，避免修改外部数据源
    for (var item in widget.rows) {
      // 使用 toJson 和 fromJson 创建新对象
      final copiedItem = ModelQuickBetSet.fromJson(item.toJson());
      rows.add(copiedItem);

      // 为每行创建 TextEditingController
      final controller = TextEditingController(
        text: ((copiedItem.amount ?? 0) ~/ 1000000).toString(),
      );
      controllers.add(controller);
    }
  }

  @override
  void dispose() {
    // 释放所有控制器
    for (var controller in controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  // 获取限额范围（显示单位）
  (int min, int max) _getLimitRange() {
    final symbol = AppUserManager().currentWalletRx.value.symbol ?? 'TRX';
    final betLimit = widget.gameLogic.gameRoundRx.value.betLimit;

    ModelGameRoundConfigKey? limitConfig;
    if (symbol == 'USDT') {
      limitConfig = betLimit?.pageBetLimitForUSDTConfigKey;
    } else {
      limitConfig = betLimit?.pageBetLimitForTRXConfigKey;
    }

    final minMicro = limitConfig?.min ?? 0;
    final maxMicro = limitConfig?.max ?? 999999999999;

    return ((minMicro ~/ 1000000), (maxMicro ~/ 1000000));
  }

  // 计算智能步长
  int _getStepValue(int currentValue) {
    return 1;
    // if (currentValue < 100) {
    //   return 10;
    // } else if (currentValue < 1000) {
    //   return 100;
    // } else {
    //   return 1000;
    // }
  }

  // 减少金额
  void _decreaseAmount(int index) {
    final currentValue = (rows[index].amount ?? 0) ~/ 1000000;
    final step = _getStepValue(currentValue);
    final (minLimit, maxLimit) = _getLimitRange();

    // 计算新值并限制在范围内
    final newValue = (currentValue - step).clamp(minLimit, maxLimit);

    setState(() {
      rows[index].amount = newValue * 1000000;
      controllers[index].text = newValue.toString();
    });
  }

  // 增加金额
  void _increaseAmount(int index) {
    final currentValue = (rows[index].amount ?? 0) ~/ 1000000;
    final step = _getStepValue(currentValue);
    final (minLimit, maxLimit) = _getLimitRange();

    // 计算新值并限制在范围内
    final newValue = (currentValue + step).clamp(minLimit, maxLimit);

    setState(() {
      rows[index].amount = newValue * 1000000;
      controllers[index].text = newValue.toString();
    });
  }

  // 从输入框更新金额
  void _updateAmountFromInput(int index, String value) {
    final intValue = int.tryParse(value) ?? 0;
    final (minLimit, maxLimit) = _getLimitRange();

    // 限制在范围内
    // final clampedValue = intValue.clamp(minLimit, maxLimit);
    setState(() {
      if (intValue > maxLimit) {
        LoadingUtils.showToast(LocaleKeys.quickAmountConfigErrorMaxValue.tr
            .trArgs([maxLimit.toString()]));
        rows[index].amount = maxLimit * 1000000;
        controllers[index].text= maxLimit.toString();

      } else {
        rows[index].amount = intValue * 1000000;
      }
    });

    // setState(() {
    //   rows[index].amount = clampedValue * 1000000;
    //   // 如果输入值超出范围，更新输入框显示为限制后的值
    //   if (clampedValue != intValue) {
    //
    //
    //     final symbol = AppUserManager().currentWalletRx.value.symbol ?? 'TRX';
    //     final betLimit = widget.gameLogic.gameRoundRx.value.betLimit;
    //
    //     ModelGameRoundConfigKey? limitConfig;
    //     if (symbol == 'USDT') {
    //       limitConfig = betLimit?.pageBetLimitForUSDTConfigKey;
    //     } else {
    //       limitConfig = betLimit?.pageBetLimitForTRXConfigKey;
    //     }
    //
    //     // final minMicro = limitConfig?.min ?? 0;
    //     final maxMicro = limitConfig?.max ?? 999999999999;
    //     if (intValue > maxLimit) {
    //       controllers[index].text = clampedValue.toString();
    //       LoadingUtils.showToast(LocaleKeys.quickAmountConfigErrorMaxValue.tr
    //           .trArgs([(maxMicro ~/ 1000000).toString()]));
    //     } else {
    //       // LoadingUtils.showToast(LocaleKeys.quickAmountConfigErrorMinValue.tr
    //       //     .trArgs([(minMicro ~/ 1000000).toString()]));
    //     }
    //   }
    // });
  }

  // 删除行
  void _deleteRow(int index) {
    if (rows.length <= 5) {
      LoadingUtils.showToast(LocaleKeys.minQuickAmountLimit.tr);
    } else {
      setState(() {
        controllers[index].dispose();
        controllers.removeAt(index);
        rows.removeAt(index);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          Expanded(
              child: SingleChildScrollView(
            child: Column(
                children: rows.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;

              return Container(
                margin: EdgeInsets.only(bottom: 12.w),
                child: Row(
                  children: [
                    // 左侧显示框（只读）
                    Container(
                      width: 80.w,
                      height: 44.w,
                      decoration: BoxDecoration(
                        color: AppColor.color2D2F35,
                        borderRadius: BorderRadius.circular(8.w),
                        border: Border(
                          bottom: BorderSide(
                            color: AppColor.textPrimary.withOpacity(0.15),
                            width: 1.w,
                          ),
                        ),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        ((item.amount ?? 0) ~/ 1000000).toString(),
                        style: TextStyle(
                          color: AppColor.textPrimary.withOpacity(0.94),
                          fontWeight: FontWeight.w500,
                          fontSize: 16.sp,
                        ),
                      ),
                    ),
                    12.horizontalSpace,

                    // 中间控制区域（减号、输入框、加号）
                    Expanded(
                      child: Row(
                        children: [
                          // 减号按钮
                          DebounceGestureDetector(
                            onTap: () => _decreaseAmount(index),
                            child: AutoImage(
                              Assets.gameBetSettingOdd,
                              width: 44.w,
                            ),
                          ),
                          4.horizontalSpace,

                          // 输入框
                          Expanded(
                            child: Container(
                              height: 44.w,
                              decoration: BoxDecoration(
                                color: Colors.black.withOpacity(0.3),
                                borderRadius: BorderRadius.circular(8.w),
                                border: Border(
                                  bottom: BorderSide(
                                    color:
                                        AppColor.textPrimary.withOpacity(0.15),
                                    width: 1.w,
                                  ),
                                ),
                              ),
                              child: CommonTextField(
                                textEditingController: controllers[index],
                                textAlign: TextAlign.center,
                                keyboardType: TextInputType.number,
                                inputFormatters: [
                                  // 首位不能是0，正则：非零开头的数字

                                  FilteringTextInputFormatter.allow(
                                      RegExp(r'^[1-9]\d*|$')),
                                ],
                                style: TextStyle(
                                  color: AppColor.textPrimary.withOpacity(0.94),
                                  fontWeight: FontWeight.w500,
                                  fontSize: 16.sp,
                                ),
                                // decoration: const InputDecoration(
                                //   border: InputBorder.none,
                                //   contentPadding: EdgeInsets.zero,
                                // ),
                                onChanged: (value) =>
                                    _updateAmountFromInput(index, value),
                              ),
                            ),
                          ),
                          4.horizontalSpace,

                          // 加号按钮
                          DebounceGestureDetector(
                            onTap: () => _increaseAmount(index),
                            child: AutoImage(
                              Assets.gameBetSettingAdd,
                              width: 44.w,
                            ),
                          ),
                        ],
                      ),
                    ),
                    12.horizontalSpace,

                    // 右侧删除按钮
                    DebounceGestureDetector(
                      onTap: () => _deleteRow(index),
                      child: SizedBox(
                        height: 28.w,
                        width: 28.w,
                        child: Center(
                          child: AutoImage(
                            Assets.gameBetSettingDel,
                            width: 24.w,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            }).toList()),
          )),
          24.verticalSpaceFromWidth,
          Row(
            children: [
              Expanded(
                  child: CommonButton(
                title: LocaleKeys.addQuickAmount.tr,
                enable: false,
                height: 44.w,
                alwaysCanClick: true,
                onClick: () {
                  if (rows.length < 10) {
                    final (minLimit, maxLimit) = _getLimitRange();
                    rows.add(ModelQuickBetSet(amount: minLimit * 1000000));
                    final controller = TextEditingController(
                      text: minLimit.toString(),
                    );
                    controllers.add(controller);
                    if (mounted) {
                      setState(() {});
                    }
                  } else {
                    LoadingUtils.showToast(LocaleKeys.maxQuickAmountLimit.tr);
                  }
                },
              )),
              12.horizontalSpace,
              Expanded(
                  child: CommonButton(
                title: LocaleKeys.save.tr,
                height: 44.w,
                onClick: () {
                  final (minLimit, maxLimit) = _getLimitRange();

                  List<int?> amounts = rows.map((item) => item.amount).toList();
                  String? toast;
                  for (var amount in amounts) {
                    if ((amount ?? 0) < minLimit *1000000) {
                      toast = LocaleKeys.quickAmountConfigErrorMinValue.tr
                          .trArgs([(minLimit).toString()]);
                      break;
                    }
                  }

                  if (toast != null) {
                    LoadingUtils.showToast(toast);
                  } else {
                    widget.logic.postQuickBetSetting(rows);
                  }
                },
              )),
            ],
          )
        ],
      ),
    );
  }
}
